1 : <?php
2 : /*--------------------------------------------------------------------------+
3 : This file is part of eStudy.
4 : common/ez_sql.inc.php
5 : - Modulgruppe: Framework
6 : - Beschreibung: ezSQL-Klasse für einfachen Datenbankzugriff.
7 : Original von Justin Vincent (s.u.) mit kleinen Anpassungen.
8 : - Version: 0.1, 04/10/05
9 : - Autor(en): Justin Vincent <justin@visunet.ie>,
10 : Clemens Weiß <clemens.weiss@mni.fh-giessen.de>
11 : +---------------------------------------------------------------------------+
12 : This program is free software; you can redistribute it and/or
13 : modify it under the terms of the GNU General Public License
14 : as published by the Free Software Foundation; either version 2
15 : of the License, or any later version.
16 : +---------------------------------------------------------------------------+
17 : This program is distributed in the hope that it will be useful,
18 : but WITHOUT ANY WARRANTY; without even the implied warranty of
19 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 : GNU General Public License for more details.
21 : You should have received a copy of the GNU General Public License
22 : along with this program; if not, write to the Free Software
23 : Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 : +--------------------------------------------------------------------------*/
25 : /**
26 : * Implementierung der ezSQL-Klasse und Objekterzeugung für den
27 : * Datenbankzugriff.
28 : *
29 : * @package eStudy.Framework
30 : * @version 0.1, 04/10/05
31 : * @author Justin Vincent <justin@visunet.ie>
32 : * @author Clemens Weiß <clemens.weiss@mni.fh-giessen.de>
33 : */
34 : // ==================================================================
35 : // Author: Justin Vincent (justin@visunet.ie)
36 : // Web: http://php.justinvincent.com
37 : // Name: ezSQL
38 : // Desc: Class to make it very easy to deal with mySQL database connections.
39 : //
40 : // !! IMPORTANT !!
41 : //
42 : // Please send me a mail telling me what you think of ezSQL
43 : // and what your using it for!! Cheers. [ justin@visunet.ie ]
44 : //
45 : // ==================================================================
46 : // User Settings -- CHANGE HERE
47 : define("EZSQL_DB_USER", $settings["dbUser"]); // <-- mysql db user
48 : define("EZSQL_DB_PASSWORD", $settings["dbPassword"]); // <-- mysql db password
49 : define("EZSQL_DB_NAME", $settings["dbName"]); // <-- mysql db pname
50 : define("EZSQL_DB_HOST", $settings["dbHost"].":".$settings["dbPort"]); // <-- mysql server host
51 : // ==================================================================
52 : // ezSQL Constants
53 : define("EZSQL_VERSION", "1.26");
54 : define("OBJECT", "OBJECT", true);
55 : define("ARRAY_A", "ARRAY_A", true);
56 : define("ARRAY_N", "ARRAY_N", true);
57 : // ==================================================================
58 : // The Main Class
59 : class ezdb {
60 : var $trace = false; // same as $debug_all
61 : var $debug_all = false; // same as $trace
62 : var $show_errors = true;
63 : var $num_queries = 0;
64 : var $last_query;
65 : var $col_info;
66 : var $debug_called;
67 : var $vardump_called;
68 : // ==================================================================
69 : // DB Constructor - connects to the server and selects a database
70 : function ezdb($dbuser, $dbpassword, $dbname, $dbhost, $showErrors = true) {
71 0 : $this->show_errors = $showErrors;
72 0 : $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword);
73 0 : if (!$this->dbh) {
74 0 : $this->print_error("<b>Error establishing a database connection!</b><ol><li>Are you sure you have the correct user/password?</li><li>Are you sure that you have typed the correct hostname?</li><li>Are you sure that the database server is running?</li></ol>");
75 0 : }
76 0 : mysql_set_charset("utf8", $this->dbh);
77 0 : $this->select($dbname);
78 0 : }
79 : // ==================================================================
80 : // Select a DB (if another one needs to be selected)
81 : function select($db) {
82 0 : if (!@mysql_select_db($db, $this->dbh)) {
83 0 : $this->print_error("<b>Error selecting database <u>$db</u>!</b><ol><li>Are you sure it exists?</li><li>Are you sure there is a valid database connection?</li></ol>");
84 0 : }
85 0 : }
86 : // ====================================================================
87 : // Format a string correctly for safe insert under all PHP conditions
88 : function escape($str) {
89 0 : return mysql_escape_string(stripslashes($str));
90 : }
91 : // ==================================================================
92 : // Print SQL/DB error.
93 : function print_error($str = "") {
94 : // All erros go to the global error array $EZSQL_ERROR..
95 0 : global $EZSQL_ERROR;
96 : // If no special error string then use mysql default..
97 0 : if (!$str) {
98 0 : $str = mysql_error($this->dbh);
99 0 : $error_no = mysql_errno($this->dbh);
100 0 : } else {
101 0 : $error_no = 0;
102 : }
103 : // Log error to file
104 0 : $logfile = @fopen(PATH_TO_ROOT."logs/sql-".date("Y-m-d") .".log", "a");
105 0 : if ($logfile) {
106 0 : fwrite($logfile, date("H:i:s") ."\n");
107 0 : if (isset($_SERVER["REQUEST_URI"])) fwrite($logfile, "Script: ".$_SERVER["REQUEST_URI"]."\n");
108 0 : if (isset($_SESSION["userid"])) {
109 0 : fwrite($logfile, "User: ".$_SESSION["userid"]." (".$_SESSION["username"]."), Course: ".$_SESSION["course"]."\n");
110 0 : }
111 0 : fwrite($logfile, "Query: $this->last_query\n");
112 0 : fwrite($logfile, "Error String: $str\n");
113 0 : fwrite($logfile, "Error Number: $error_no\n\n");
114 0 : fclose($logfile);
115 0 : }
116 : // Log this error to the global array..
117 0 : $EZSQL_ERROR[] = array("query" => $this->last_query, "error_str" => $str, "error_no" => $error_no);
118 : // Is error output turned on or not..
119 0 : if ($this->show_errors) {
120 : // If there is an error then take note of it
121 0 : print "<p style='color: #f00;'>";
122 0 : print "<b>SQL/DB Error --</b> ";
123 0 : print "[<span style='color: #007;'>$str</span>]";
124 0 : print "</p>";
125 0 : } else {
126 0 : return false;
127 : }
128 0 : }
129 : // ==================================================================
130 : // Turn error handling on or off..
131 : function show_errors() {
132 0 : $this->show_errors = true;
133 0 : }
134 : function hide_errors() {
135 0 : $this->show_errors = false;
136 0 : }
137 : // ==================================================================
138 : // Kill cached query results
139 : function flush() {
140 : // Get rid of these
141 4 : $this->last_result = null;
142 4 : $this->col_info = null;
143 4 : $this->last_query = null;
144 4 : }
145 : // ==================================================================
146 : // Basic Query - see docs for more detail
147 : function query($query) {
148 : // For reg expressions
149 4 : $query = trim($query);
150 : // initialise return
151 4 : $return_val = 0;
152 : // Flush cached values..
153 4 : $this->flush();
154 : // Log how the function was called
155 4 : $this->func_call = "\$db->query(\"$query\")";
156 : // Keep track of the last query for debug..
157 4 : $this->last_query = $query;
158 : // Perform the query via std mysql_query function..
159 4 : $this->result = @mysql_query($query, $this->dbh);
160 4 : $this->num_queries++;
161 : // If there is an error then take note of it..
162 4 : if (is_resource($this->dbh) && mysql_error($this->dbh)) {
163 0 : $this->print_error();
164 0 : return false;
165 : }
166 : // Query was an insert, delete, update, replace
167 4 : if (is_resource($this->dbh) && preg_match("/^(insert|delete|update|replace)\s+/i", $query)) {
168 0 : $this->rows_affected = mysql_affected_rows($this->dbh);
169 : // Take note of the insert_id
170 0 : if (preg_match("/^(insert|replace)\s+/i", $query)) {
171 0 : $this->insert_id = mysql_insert_id($this->dbh);
172 0 : }
173 : // Return number fo rows affected
174 0 : $return_val = $this->rows_affected;
175 0 : }
176 : // Query was an successful select
177 4 : elseif (is_resource($this->result)) {
178 : // Take note of column info
179 4 : $i = 0;
180 4 : while ($i < @mysql_num_fields($this->result)) {
181 4 : $this->col_info[$i] = @mysql_fetch_field($this->result);
182 4 : $i++;
183 4 : }
184 : // Store Query Results
185 4 : $num_rows = 0;
186 4 : while ($row = @mysql_fetch_object($this->result)) {
187 : // Store relults as an objects within main array
188 3 : $this->last_result[$num_rows] = $row;
189 3 : $num_rows++;
190 3 : }
191 4 : @mysql_free_result($this->result);
192 : // Log number of rows the query returned
193 4 : $this->num_rows = $num_rows;
194 : // Return number of rows selected
195 4 : $return_val = $this->num_rows;
196 4 : }
197 : // Query was not successful
198 : else {
199 0 : $this->num_rows = 0;
200 0 : $return_val = 0;
201 : }
202 : // If debug ALL queries
203 4 : $this->trace || $this->debug_all ? $this->debug() : null;
204 4 : return $return_val;
205 : }
206 : // ==================================================================
207 : // Get one variable from the DB - see docs for more detail
208 : function get_var($query = null, $x = 0, $y = 0) {
209 : // Log how the function was called
210 3 : $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
211 : // If there is a query then perform it if not then use cached results..
212 3 : if ($query) {
213 3 : $this->query($query);
214 3 : }
215 : // Extract var out of cached results based x,y vals
216 3 : if ($this->last_result[$y]) {
217 3 : $values = array_values(get_object_vars($this->last_result[$y]));
218 3 : }
219 : // If there is a value return it else return null
220 3 : return (isset($values[$x]) && $values[$x] !== '') ? $values[$x] : null;
221 : }
222 : // ==================================================================
223 : // Get one row from the DB - see docs for more detail
224 : function get_row($query = null, $output = OBJECT, $y = 0) {
225 : // Log how the function was called
226 2 : $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
227 : // If there is a query then perform it if not then use cached results..
228 2 : if ($query) {
229 2 : $this->query($query);
230 2 : }
231 : // If the output is an object then return object using the row offset..
232 2 : if ($output == OBJECT) {
233 2 : return $this->last_result[$y] ? $this->last_result[$y] : null;
234 : }
235 : // If the output is an associative array then return row as such..
236 0 : elseif ($output == ARRAY_A) {
237 0 : return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
238 : }
239 : // If the output is an numerical array then return row as such..
240 0 : elseif ($output == ARRAY_N) {
241 0 : return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
242 : }
243 : // If invalid output type was specified..
244 : else {
245 0 : $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
246 : }
247 0 : }
248 : // ==================================================================
249 : // Function to get 1 column from the cached result set based in X index
250 : // see docs for usage and info
251 : function get_col($query = null, $x = 0) {
252 : // If there is a query then perform it if not then use cached results..
253 0 : if ($query) {
254 0 : $this->query($query);
255 0 : }
256 : // Extract the column values
257 0 : if ($count = count($this->last_result)) {
258 0 : for ($i = 0 ; $i < $count ; $i++) {
259 0 : $new_array[$i] = $this->get_var(null, $x, $i);
260 0 : }
261 0 : return $new_array;
262 : }
263 0 : return null;
264 : }
265 : // ==================================================================
266 : // Return the the query as a result set - see docs for more details
267 : function get_results($query = null, $output = OBJECT) {
268 : // Log how the function was called
269 1 : $this->func_call = "\$db->get_results(\"$query\", $output)";
270 : // If there is a query then perform it if not then use cached results..
271 1 : if ($query) {
272 1 : $this->query($query);
273 1 : }
274 : // Send back array of objects. Each row is an object
275 1 : if ($output == OBJECT) {
276 0 : return $this->last_result;
277 1 : } elseif ($output == ARRAY_A || $output == ARRAY_N) {
278 1 : if ($this->last_result) {
279 0 : $i = 0;
280 0 : foreach($this->last_result as $row) {
281 0 : $new_array[$i] = get_object_vars($row);
282 0 : if ($output == ARRAY_N) {
283 0 : $new_array[$i] = array_values($new_array[$i]);
284 0 : }
285 0 : $i++;
286 0 : }
287 0 : return $new_array;
288 : } else {
289 1 : return null;
290 : }
291 : }
292 0 : }
293 : // ==================================================================
294 : // Function to get column meta data info pertaining to the last query
295 : // see docs for more info and usage
296 : function get_col_info($info_type = "name", $col_offset = -1) {
297 0 : if ($this->col_info) {
298 0 : if ($col_offset == -1) {
299 0 : $i = 0;
300 0 : foreach($this->col_info as $col) {
301 0 : $new_array[$i] = $col->{$info_type};
302 0 : $i++;
303 0 : }
304 0 : return $new_array;
305 : } else {
306 0 : return $this->col_info[$col_offset]->{$info_type};
307 : }
308 : }
309 0 : }
310 : // ==================================================================
311 : // Dumps the contents of any input variable to screen in a nicely
312 : // formatted and easy to understand way - any type: Object, Var or Array
313 : function vardump($mixed = '') {
314 0 : echo "<p style='color: #000090;'>";
315 0 : echo "<pre>";
316 0 : if (!$this->vardump_called) {
317 0 : echo "<span style='color: #800080'><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></span>\n\n";
318 0 : }
319 0 : $var_type = gettype($mixed);
320 0 : print_r(($mixed ? $mixed : "<span style='color: red;'>No Value / False</span>"));
321 0 : echo "\n\n<b>Type:</b> ".ucfirst($var_type) ."\n";
322 0 : echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query ? $this->last_query : "NULL") ."\n";
323 0 : echo "<b>Last Function Call:</b> ".($this->func_call ? $this->func_call : "None") ."\n";
324 0 : echo "<b>Last Rows Returned:</b> ".count($this->last_result) ."\n";
325 0 : echo "</pre></p>".$this->donation();
326 0 : $this->vardump_called = true;
327 0 : }
328 : // Alias for the above function
329 : function dumpvar($mixed) {
330 0 : $this->vardump($mixed);
331 0 : }
332 : // ==================================================================
333 : // Displays the last query string that was sent to the database & a
334 : // table listing results (if there were any).
335 : // (abstracted into a seperate file to save server overhead).
336 : function debug() {
337 : // Only show ezSQL credits once..
338 0 : if (!$this->debug_called) {
339 0 : echo "<span style='color: #800080;'><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></span><p>\n";
340 0 : }
341 0 : echo "<span style='color: #000099;'><b>Query</b> [$this->num_queries] <b>--</b> ";
342 0 : echo "[<span style='color: #000;'><b>$this->last_query</b></span>]</span><p>";
343 0 : echo "<span style='color: #000099;'><b>Query Result..</b></span>";
344 0 : if ($this->col_info) {
345 : // =====================================================
346 : // Results top rows
347 0 : echo "<table cellpadding='5' cellspacing='0'>";
348 0 : echo "<tr style='background-color: #eee; vertical-align: bottom; color: #559'><td><b>(row)</b></td>";
349 0 : $count = count($this->col_info);
350 0 : for ($i = 0 ; $i < $count ; $i++) {
351 0 : echo "<td>{$this->col_info[$i]->type} {$this->col_info[$i]->max_length}</font><br /><b>{$this->col_info[$i]->name}</b></td>";
352 0 : }
353 0 : echo "</tr>";
354 : // ======================================================
355 : // print main results
356 0 : if ($this->last_result) {
357 0 : $i = 0;
358 0 : foreach($this->get_results(null, ARRAY_N) as $one_row) {
359 0 : $i++;
360 0 : echo "<tr style='background-color: #fff'><td style='backgound-color: #eee; color: #559'>$i</td>";
361 0 : foreach($one_row as $item) {
362 0 : echo "<td>$item</td>";
363 0 : }
364 0 : echo "</tr>";
365 0 : }
366 0 : } // if last result
367 : else {
368 0 : echo "<tr style='background-color: #fff'><td colspan=".(count($this->col_info) +1) .">No Results</td></tr>";
369 : }
370 0 : echo "</table>";
371 0 : } // if col_info
372 : else {
373 0 : echo "No Results";
374 : }
375 0 : $this->debug_called = true;
376 0 : }
377 : // =======================================================
378 : // Naughty little function to ask for some remuniration!
379 : function donation() {
380 0 : return "<span style='color: #000'>If ezSQL has helped <a href=\"https://www.paypal.com/xclick/business=justin%40justinvincent.com&item_name=ezSQL&no_note=1&tax=0\" style=\"color: 0000CC;\">make a donation!?</a> [ go on! you know you want to! ]</span>";
381 : }
382 : }
|